//
//  TableViewController.m
//  iCloudBackUps
//
//  Created by razeen on 12/22/15.
//  Copyright © 2015 razeen. All rights reserved.
//
#import "JSONKit.h"
#import "iCloud.h"
#import "FMDB.h"
#import "DBService.h"
#import "UserModel.h"
#import "TableViewController.h"
#import "NSMetadataItem+sonson.h"
#import "SVProgressHUD.h"


#define CLOUD_CONTAINER_ID  @"iCloud.com.trustasia.t-shield"


@interface TableViewController ()<iCloudDelegate,iCloudDocumentDelegate>
{
    NSMutableArray *_dataArray;
}

- (IBAction)manualRefresh:(id)sender;
- (IBAction)manualDelete:(id)sender;
- (IBAction)manualShowAll:(id)sender;
- (IBAction)manualLocalDelete:(id)sender;

@end

@implementation TableViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    _dataArray = [[NSMutableArray alloc]initWithArray:[[DBService shareDB] queryAccount]];
    
    //设置基本的代理，和
    [[iCloud sharedCloud] setDelegate:self];
    [[iCloud sharedCloud] setVerboseLogging:YES];
    
    //设置容器为第一个
    [[iCloud sharedCloud] setupiCloudDocumentSyncWithUbiquityContainer:CLOUD_CONTAINER_ID];
    
    
    //查看iCloud是否可用
//    BOOL cloudIsAvailable = [[iCloud sharedCloud] checkCloudAvailability];
//    
//    if (cloudIsAvailable) {
//        
//        NSLog(@"[viewcontroller] iCloud is Available");
//        
//    }else{
//        
//        NSLog(@"[viewcontroller] iCloud is UnAvailable");
//    }
    
    //查看iCloudContainer是否可用
//    BOOL cloudContainerIsAvailable = [[iCloud sharedCloud] checkCloudUbiquityContainer];
//    
//    if (cloudContainerIsAvailable) {
//        
//        NSLog(@"[viewcontroller] iCloud Container is Available ");
//        
//    }else{
//        
//        NSLog(@"[viewcontroller] iCloud Container is UnAvailable");
//    }

}

- (void)viewWillAppear:(BOOL)animated{
   
    [super viewWillAppear:animated];
   
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveLocalToCloud) name:@"savetocloud" object:nil];

}


- (void)dealloc{

    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"savetocloud" object:nil];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}



#pragma mark - user click
- (IBAction)manualRefresh:(id)sender {

    [[iCloud sharedCloud] updateFiles];//手动刷新
    
    
}

- (IBAction)manualDelete:(id)sender {
    
    [[iCloud sharedCloud] deleteDocumentWithName:@"userdata" completion:^(NSError *error) {
       
        if (error == nil) {
            
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"删除成功" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
            
            [alert show];
        }else {
            
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:error.description delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
            
            [alert show];
        }
    }];
}

- (IBAction)manualShowAll:(id)sender {
    
    NSArray *array = [[iCloud sharedCloud] listCloudFiles];
    
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:[NSString stringWithFormat:@"云上有%ld个文件",array.count] delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
    
    [alert show];
    
    
}

- (IBAction)manualLocalDelete:(id)sender {
    
    [[DBService shareDB] deleteAllFile];
    
    _dataArray = [NSMutableArray arrayWithArray:[[DBService shareDB] queryAccount]];
    
    [self.tableView reloadData];
    
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"已完成" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
    
    
    [alert show];
}

#pragma mark - some ....

//本地添加数据的时候调用
- (void)saveLocalToCloud{

    //获取本地
    NSArray *daArray = [[DBService shareDB] queryAccount];
    
    
    //本地的装换成json
    NSMutableArray *dicArray = [[NSMutableArray alloc]initWithCapacity:0];
    
    for (UserModel *model in daArray) {
        
        NSDictionary *dic = @{@"id":@(model.userID),@"appName":model.appName,@"account":model.userAccount,@"key":model.userkey};
        
        [dicArray addObject:dic];
        
    }
    
    //将转换好的上传到云
    NSError *error;
    
    NSData *data = [NSJSONSerialization dataWithJSONObject:dicArray options:NSJSONWritingPrettyPrinted error:&error];
    
    [[iCloud sharedCloud] saveAndCloseDocumentWithName:@"userdata" withContent:data completion:^(UIDocument *cloudDocument, NSData *documentData, NSError *error) {
        
        if (error == nil) {
            
            
        }
    }];
}


- (void)showDetail{
    
    _dataArray = [NSMutableArray arrayWithArray:[[DBService shareDB] queryAccount]];
    
    [self.tableView reloadData];
    
}

- (void)solveConflict{
    
    NSArray *conflict = [[iCloud sharedCloud] findUnresolvedConflictingVersionsOfFile:@"userdata"];
    
    [[iCloud sharedCloud]resolveConflictForFile:@"userdata" withSelectedFileVersion:conflict.lastObject];
    
}




#pragma mark - iCloud Delegate 
- (void)iCloudAvailabilityDidChangeToState:(BOOL)cloudIsAvailable withUbiquityToken:(id)ubiquityToken withUbiquityContainer:(NSURL *)ubiquityContainer{
    
//    NSLog(@"\n -----cloudIsAvailable:%d",cloudIsAvailable);
//    NSLog(@"\n -----ubiqutyToken:%@",ubiquityToken);
//    NSLog(@"\n -----uibquityContainer:%@",ubiquityContainer);
    
}


- (void)iCloudDidFinishInitializingWitUbiquityToken:(id)cloudToken withUbiquityContainer:(NSURL *)ubiquityContainer{
    
    
    
}

- (void)iCloudFileUpdateDidBegin{
   
    [SVProgressHUD show];
    
}


- (void)iCloudFilesDidChange:(NSMutableArray *)files withNewFileNames:(NSMutableArray *)fileNames{
    
    [self solveConflict];

    for (NSMetadataItem *metaDataItem in files) {
        
        [metaDataItem dump];

        NSString *fileName = [metaDataItem valueForAttribute:NSMetadataItemFSNameKey];

        if ([fileName isEqualToString:@"userdata"]) {
            
            NSURL *url = [metaDataItem valueForKey:NSMetadataItemURLKey];
            
            NSData *data = [NSData dataWithContentsOfURL:url];
            
            NSError *error;
            
            NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
            
            //云上的数据的有更改后插入本地数据库
            
            if ([[DBService shareDB] saveNotModelArrayintoDB:array]) {
                NSLog(@"save success");
                
                _dataArray = [NSMutableArray arrayWithArray:[[DBService shareDB] queryAccount]];
                
                [self.tableView reloadData];
                

            }
        }
    }
}


- (void)iCloudFileUpdateDidEnd{

    [SVProgressHUD dismiss];
    
}

- (void)iCloudDocumentErrorOccured:(NSError *)error{
    
    NSLog(@"line221:DocumentErrorOccured");

    
}

- (void)iCloudFileConflictBetweenCloudFile:(NSDictionary *)cloudFile andLocalFile:(NSDictionary *)localFile{
    
    NSLog(@"line202:conflict");

}





#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 3;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CELL" forIndexPath:indexPath];
    
    UserModel *model = _dataArray[indexPath.section];
    
    if (indexPath.row == 0 ) {
        
        cell.textLabel.text = [NSString stringWithFormat:@"AppName:%@",model.appName];
    
    }
    if (indexPath.row == 1 ) {
        
        cell.textLabel.text = [NSString stringWithFormat:@"account:%@",model.userAccount];
        
    }
    if (indexPath.row == 2 ) {
        
        cell.textLabel.text = [NSString stringWithFormat:@"sercet:%@",model.userkey];
        
    }
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 20)];
    label.backgroundColor = [UIColor brownColor];
    label.text = [NSString stringWithFormat:@"%d",(int)section];
    return label;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 22;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 20;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.0000001;
}
- (void)ALL{
    /*
     NSMetadataQuery *query = [iCloud sharedCloud].query;
     NSMutableArray *fileList = [iCloud sharedCloud].fileList;
     NSMutableArray *previousQueryResults = [iCloud sharedCloud].previousQueryResults;
     
     [[iCloud sharedCloud] checkCloudAvailability];
     [[iCloud sharedCloud] checkCloudUbiquityContainer];
     NSURL *url = [[iCloud sharedCloud]ubiquitousContainerURL];
     NSURL *url2 = [[iCloud sharedCloud]ubiquitousDocumentsDirectoryURL];
     [[iCloud sharedCloud] updateFiles];
     [[iCloud sharedCloud] saveAndCloseDocumentWithName:@"" withContent:@"" completion:^(UIDocument *cloudDocument, NSData *documentData, NSError *error) {
     
     }];
     [[iCloud sharedCloud] uploadLocalDocumentToCloudWithName:@"" completion:^(NSError *error) {
     
     }];
     [[iCloud sharedCloud] uploadLocalOfflineDocumentsWithRepeatingHandler:^(NSString *documentName, NSError *error) {
     
     } completion:^{
     
     }];
     NSURL *url3 = [[iCloud sharedCloud] shareDocumentWithName:@"" completion:^(NSURL *sharedURL, NSDate *expirationDate, NSError *error) {
     
     }];
     [[iCloud sharedCloud] deleteDocumentWithName:@"" completion:^(NSError *error) {
     
     }];
     [[iCloud sharedCloud] evictCloudDocumentWithName:@"" completion:^(NSError *error) {
     
     }];
     [[iCloud sharedCloud] retrieveCloudDocumentObjectWithName:@""];
     [[iCloud sharedCloud] retrieveCloudDocumentWithName:@"" completion:^(UIDocument *cloudDocument, NSData *documentData, NSError *error) {
     
     }];
     BOOL isExist = [[iCloud sharedCloud] doesFileExistInCloud:@""];
     NSNumber *num = [[iCloud sharedCloud] fileSize:@""];
     NSDate *date = [[iCloud sharedCloud] fileCreatedDate:@""];
     NSDate *date2 = [[iCloud sharedCloud] fileModifiedDate:@""];
     NSArray *list = [[iCloud sharedCloud] listCloudFiles];
     
     [[iCloud sharedCloud] renameOriginalDocument:@"" withNewName:@"" completion:^(NSError *error) {
     
     }];
     [[iCloud sharedCloud] duplicateOriginalDocument:@"" withNewName:@"" completion:^(NSError *error) {
     
     }];
     [[iCloud sharedCloud] documentStateForFile:@"" completion:^(UIDocumentState *documentState, NSString *userReadableDocumentState, NSError *error) {
     
     }];
     
     BOOL stop2 = [[iCloud sharedCloud] monitorDocumentStateForFile:@"" onTarget:self withSelector:@selector(mainBundle)];
     BOOL stop = [[iCloud sharedCloud] stopMonitoringDocumentStateChangesForFile:@"" onTarget:self];
     NSArray *conflict = [[iCloud sharedCloud] findUnresolvedConflictingVersionsOfFile:@""];
     [[iCloud sharedCloud] resolveConflictForFile:@"" withSelectedFileVersion:@""];
     */
    
    
}


@end
